﻿/*************************************
* 类名：TenantController
* 作者：realyrare
* 邮箱：mahonggang8888@126.com
* 时间：2021/3/11 17:22:57
*┌───────────────────────────────────┐　    
*│　   版权所有：神牛软件　　　　	     │
*└───────────────────────────────────┘
**************************************/
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using ShenNius.Caches;
using ShenNius.Repository;
using ShenNius.Sys.API.Domain.Entity;
using ShenNius.Sys.API.Domain.Repository;
using ShenNius.Sys.API.Dtos.Common;
using ShenNius.Sys.API.Dtos.Input;
using ShenNius.Sys.API.Infrastructure;
using ShenNius.Sys.API.Infrastructure.Attributes;
using ShenNius.Sys.API.Infrastructure.Common;
using ShenNius.Sys.API.Infrastructure.Configs;
using System;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace ShenNius.Sys.API.Controllers
{
    [Route("api/sys/[controller]/[action]")]
    public class TenantController : ApiBaseController<Tenant, DetailQuery, DeletesInput, KeyListQuery, TenantInput, TenantModifyInput>
    {
        private readonly IBaseRepository<Tenant> _repository;
        private readonly IDistributedCache _cacheHelper;
        private readonly ICurrentUserContext _currentUserContext;
        private readonly IRecycleRepository _recycleRepository;

        public TenantController(IBaseRepository<Tenant> repository, IMapper mapper, IDistributedCache cacheHelper, ICurrentUserContext currentUserContext, IRecycleRepository recycleRepository) : base(repository, mapper)
        {
            _repository = repository;
            _cacheHelper = cacheHelper;
            _currentUserContext = currentUserContext;
            _recycleRepository = recycleRepository;
        }
        //[HttpGet, Authority]
        //public override async Task<ApiResult> Detail([FromQuery] DetailQuery detailQuery)
        //{
        //    var res = await _repository.GetModelAsync(d => d.Id == detailQuery.Id && d.Status == false&&d.IsDeleted==false);
        //    return new ApiResult(data: res);
        //}
        //[HttpDelete, Authority]
        //public override async Task<ApiResult> Deletes([FromBody] DeletesInput deletesInput)
        //{
        //    foreach (var item in deletesInput.Ids)
        //    {
        //        await _repository.UpdateAsync(d => new Tenant() { Status = false }, d => d.Id == item);
        //    }
        //    return new ApiResult();
        //}
        /// <summary>
        /// 设置当前站点
        /// </summary>
        /// <param name="TenantCurrentInput"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<ApiResult> SetCurrent([FromBody] TenantCurrentInput TenantCurrentInput)
        {
            //把之前缓存存储的站点拿出来设置为不是当前的。
            var model = await _repository.GetModelAsync(d => d.Id == TenantCurrentInput.Id && d.Status == false && d.IsCurrent == false && d.IsDeleted == false);
            if (model == null)
            {
                throw new ArgumentNullException("当前站点实体信息为空!");
            }
            var currentTenantId = _cacheHelper.Get<int>($"{SysCacheKey.CurrentTenant}:{_currentUserContext.Id}");
            if (currentTenantId != 0)
            {
                await _repository.UpdateAsync(d => new Tenant() { IsCurrent = false }, d => d.Id == currentTenantId);
            }

            model.IsCurrent = true;
            await _repository.UpdateAsync(model);
            //这里最好更新下缓存
            _cacheHelper.Set($"{SysCacheKey.CurrentTenant}:{_currentUserContext.Id}", model);
            return new ApiResult();
        }
        [HttpGet]
        public async Task<ApiResult> GetList()
        {
            //首页加载该列表时赋值于缓存
            var res = await _repository.GetListAsync(d => d.Status == false && !d.IsDeleted);
            foreach (var item in res)
            {
                if (item.IsCurrent)
                {
                    _cacheHelper.Set($"{SysCacheKey.CurrentTenant}:{_currentUserContext.Id}", item.Id);
                }
            }
            return new ApiResult(data: res);
        }
        [HttpGet, Authority]
        public override async Task<ApiResult> GetListPages([FromQuery] KeyListQuery keyListQuery)
        {
            Expression<Func<Tenant, bool>> whereExpression = d => !d.IsDeleted;
            if (!string.IsNullOrEmpty(keyListQuery.Key))
            {
                whereExpression = d => d.Title.Contains(keyListQuery.Key) && !d.IsDeleted;
            }
            var res = await _repository.GetPagesAsync(keyListQuery.Page, keyListQuery.Limit, whereExpression, d => d.Id, false);
            return new ApiResult(data: new { count = res.TotalItems, items = res.Items });
        }
        [HttpDelete, Authority(Action = nameof(Button.Delete))]
        public virtual Task<ApiResult> SoftDelete([FromBody] DeletesInput deleteInput)
        {
            return _recycleRepository.SoftDeleteAsync(deleteInput, _repository);
        }
    }
}